﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Configuration;
using Newtonsoft.Json;
using Swallow.Entity;
using Microsoft.AspNetCore.Razor.Tokenizer;
using Swallow.Core;
using Swallow.Service;

namespace Swallow.Api {
    public class Startup {
        public Startup(IHostingEnvironment env) {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsEnvironment("Development")) {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services) {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddMvc();

            var redisConnection = ConfigurationManager.ConnectionStrings["RedisServer"].ConnectionString;

            // https://github.com/NancyFx/Nancy.Serialization.JsonNet
            services.AddTransient<JsonSerializer, CustomJsonSerializer>();

            //services.AddTransient<ITokenizer, Tokenizer>().WithConstructorArgument("configuration", (Action<Tokenizer.TokenizerConfigurator>)(configurator => {
            //    configurator.KeyExpiration(() => TimeSpan.FromDays(60));
            //    configurator.TokenExpiration(() => TimeSpan.FromDays(30));
            //    configurator.WithKeyCache(new RedisTokenKeyStore(redisConnection).WithKeyStoreName("keyStoreForApi"));
            //}));

            string connection = Configuration["DefaultConnection:ConnectionString"];
            services.AddSingleton<MongoDbContext>(provider => new MongoDbContext(connection));

            services.AddTransient<IUserDbForApi, UserDbByMongo>();
            services.AddTransient<IArticleDbForManage, ArticleDbByMongo>();
            services.AddTransient<ICaseDbForManage, CaseDbByMongo>();
            services.AddTransient<IEncryptorDecryptor, EncryptorDecryptor>();
            services.AddTransient<IVerifyCode, LeancloudVerifyCodeProvider>();
            services.AddTransient<IEmailSender, MessageSender>();
            services.AddTransient<ISmsSender, MessageSender>();
            services.AddTransient<ITranslater, YoudaoTranslater>();

            //container.Bind<IRedisClientsManager>().To<RedisManagerPool>().WithConstructorArgument("hosts", new string[] { redisConnection });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseMvc();
        }
    }
}
